//
//  SearchViewController.swift
//  YueJian
//
//  Created by mac on 2017/11/8.
//  Copyright © 2017年 MapleStory. All rights reserved.
//

import UIKit
import Alamofire
class SearchViewController: UIViewController,UISearchBarDelegate,UISearchResultsUpdating,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate{

    var historyArr:[String] = [String]()
    var resultArr:[AnyObject]?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        
        self.view.backgroundColor = UIColor.white
        let leftItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(goBack))
        self.navigationItem.leftBarButtonItem = leftItem
        self.navigationItem.titleView = searchController.searchBar
        self.view.addSubview(tableView)
//        self.navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelClick)), animated: true)
    }
    
//    @objc func cancelClick() {
//        self.searchController.isActive = false
//        self.tableView.reloadData()
//    }
    
    func searchData() {
        let id = UserDefaults.standard.string(forKey:"sessionId") ?? ""
        let paramas = ["SessionID":id, "page":1, "mod":"train", "Search_key":searchController.searchBar.text ?? ""] as [String : Any]
        print(paramas)
        Alamofire.request(URL(string: Search_Train)!, method: .post, parameters: paramas, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
      
            print(response.result.value)
            self.resultArr = response.result.value as? [AnyObject]
            self.tableView.reloadData()
            
        }
    }

    private lazy var searchController: UISearchController = {
        let search = UISearchController(searchResultsController: nil)
        search.searchResultsUpdater = self
        search.searchBar.delegate = self
        search.delegate = self
        search.searchBar.placeholder = "搜索"
        search.dimsBackgroundDuringPresentation = false
        search.hidesNavigationBarDuringPresentation = false
        
        search.searchBar.showsCancelButton = true
        
        search.searchBar.setValue("", forKey: "cancelButtonText")
        search.searchBar.sizeToFit()
        return search
    }()

    @objc func goBack() {
        self.navigationController?.popViewController(animated: true)
    }

    private lazy var tableView: UITableView = {
        let table = UITableView(frame: CGRect(x: 0, y: 0, width: Screen_Width, height: Screen_Height-64), style: .grouped)
        table.delegate = self
        table.dataSource = self
        table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        return table
    }()

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return resultArr?.count ?? 0
        }
        print(historyArr.count)
        return historyArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if searchController.isActive  {
            let dic = resultArr?[indexPath.row] as! [String:AnyObject]
            cell.textLabel?.text = dic["name"] as? String
        } else {
            print(historyArr.count)
            print(indexPath.row)
            cell.textLabel?.text = historyArr[indexPath.row]
        }
        return cell
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchController.isActive = false
        self.tableView.reloadData()
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let str = searchBar.text?.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
        if str != "" && !historyArr.contains(str!){
            historyArr.append(str!)
        }
        self.searchData()

    }
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        
    }

    
    func updateSearchResults(for searchController: UISearchController) {
        
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if !searchController.isActive {
            let button = UIButton()
            button.setTitle("清除记录", for: .normal)
            button.setTitleColor(UIColor.lightGray, for: .normal)
            button.addTarget(self, action: #selector(clearHistory), for: .touchUpInside)
            return button
        } else {
            return nil
        }
    }
    
    @objc func clearHistory() {
        self.historyArr.removeAll()
        self.tableView.reloadData()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
